package com.ksyun.seckill.util;


import com.google.common.base.Strings;
import com.ksyun.seckill.constants.BizConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.Validate;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * biz工具.
 */
@Slf4j
public final class BizUtils {

    private BizUtils() {

    }

    public static void validatePhone(String phone) {
        Validate.notBlank(Strings.nullToEmpty(phone));
        if (!ValidateUtils.isMobileExact(phone)) {
            throw new IllegalArgumentException("非法手机号");
        }
    }

    public static Integer calcVerifyCodeResult(String exp) {
        try {
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine javaScript = scriptEngineManager.getEngineByName("JavaScript");
            return (Integer) javaScript.eval(exp);
        } catch (Exception e) {
            return 0;
        }
    }

    public static String generateVerifyCode() {
        int n1 = RandomUtils.nextInt(0, 10);
        int n2 = RandomUtils.nextInt(0, 10);
        int n3 = RandomUtils.nextInt(0, 10);
        String operator1 = RandomUtils.randomSome(BizConsts.NUMERIC_OPERATORS, 1).get(0);
        String operator2 = RandomUtils.randomSome(BizConsts.NUMERIC_OPERATORS, 1).get(0);
        return n1 + operator1 + n2 + operator2 + n3;
    }

}